<?php
class Wechat_login{
    /**
     * 微信登录获取微信用户信息基础信息
     * 示例demo见 handlers/wechat_login_test.php
     */
    public function get(){
        //应用ID
        $appid = 'wx75d7dc5f9c92e40f';

        //应用密钥
        $secret = '488cc5a8b13d27c0b110c9756f5ca941';

        if(!isset($_GET['code'])){
            $scope = 'snsapi_userinfo';
            if(!isset($_GET['url'])) exit('url is empty');
            $state = urlencode($_GET['url']);
            $redirect_uri = urlencode('http://bid999.com/wechat/login');
            $wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
            header('Location:'.$wxUrl);
        }else{
            $code = $_GET['code'];
            $state = $_GET['state'];
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
            $res = json_decode($this->httpGet($url),true);
            $access_token = $res['access_token'];
            $openid = $res['openid'];
            $userinfoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
            $userinfo = json_decode($this->httpGet($userinfoUrl),true);
            $_SESSION['wechat_userinfo'] = $userinfo;
            header('Location:'.$state);
        }
    }

    /**
     * CURL发送get请求
     * @param $url string 请求的url地址
     * @return mixed 对应url响应的数据
     */
    private function httpGet($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url );
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
        return curl_exec($curl);
    }
}